﻿using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class LocalConstantRule : ILRule<LocalConstantHandle>
    {
        [ILInfo(true)]
        public string Name { get; }

        public byte[] Signature { get; }

        public LocalConstantRule(
            string name,
            byte[] signature)
            : base()
        {
            Name = name;
            Signature = signature;
        }

        public LocalConstantRule(MetadataReader reader, LocalConstantHandle localConstantHandle)
            : base(reader)
        {
            LocalConstant localConstant = reader.GetLocalConstant(localConstantHandle);
            Name = reader.GetString(localConstant.Name);
            Signature = reader.GetBlobBytes(localConstant.Signature);
        }

        public override LocalConstantHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            LocalConstantHandle localConstantHandle = builder.AddLocalConstant(
                name: Name == null ? default : builder.GetOrAddString(Name),
                signature: Signature == null ? default : builder.GetOrAddBlob(Signature));
            designer.LocalConstantNumber.Increment();
            return localConstantHandle;
        }
    }
}